# @Time    : 2019/1/14 15:11
# @Author  : xufqing
from rest_framework import serializers
from ..models import UserProfile
from rest_framework.validators import UniqueValidator


class UserListSerializer(serializers.ModelSerializer):
    '''
    用户列表的序列化
    '''
    roles = serializers.SerializerMethodField()

    def get_roles(self, obj):
        return obj.roles.values()

    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'mobile', 'email', 'image', 'department', 'post', 'superior', 'is_active',
                  'roles']
        depth = 1

class UserCreateSerializer(serializers.ModelSerializer):
    '''
    创建用户序列化
    '''
    username = serializers.CharField(label="用户名", required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=UserProfile.objects.all(), message="用户已经存在")])
    mobile = serializers.RegexField("^1[3578]\d{9}$|^147\d{8}$|^176\d{8}$")


    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'mobile', 'email', 'department', 'post','is_active','roles','password']

class UserModifySerializer(serializers.ModelSerializer):
    '''
    用户编辑的序列化
    '''
    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'mobile', 'email', 'image', 'department', 'post', 'superior', 'is_active',
                  'roles']